﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AdmLaboratorios.DTO;
using AdmLaboratorios.Business;
using System.IO.Ports;

namespace AdmLaboratorios
{
    public partial class frmValeItem : Form
    {
        public StockDTO Stock { get; set; }
        public PartnerDTO Partner { get; set; }
        public ProductoDTO Producto { get; set; }
        public ValeConsumoDevolucionItemDTO Item { get; set; }

        string RxString;

        public frmValeItem()
        {
            InitializeComponent();
        }

        private void frmValeItem_Load(object sender, EventArgs e)
        {
            if (Producto != null && Stock != null)
            {
                txProductoEnStock.Text = Stock.ToString(Producto);
                //txProductoEnStock.Text = string.Format("{0} [{1}] | {2}",
                //   this.Producto.Nombre,
                //   this.Producto.Codigo,
                //   this.Producto.Tipo);

                txCantidad.Text = this.Item.Cantidad.ToString();
                //nuCantidad.Value = this.Item.Cantidad;
                txObs.Text = this.Item.Obs;
            }


            var ports = SerialPort.GetPortNames();
            cbPuerto.Items.Clear();
            foreach (var port in ports)
                cbPuerto.Items.Add(port);
            if (cbPuerto.Items.Count > 0)
                cbPuerto.SelectedIndex = 0;
        }

        private bool Validations()
        {
            if (FormsHelper.StN(txCantidad.Text) == 0) //nuCantidad.Value == 0)
                return false;

            if (Stock == null)
                return false;

            if (Producto == null)
                return false;

            return true;
        }

        private void btStock_Click(object sender, EventArgs e)
        {
            using (frmStockSeleccion f = new frmStockSeleccion())
            {
                f.Partner = this.Partner;
                FormsHelper.CargarColumnasGrilla(f);
                if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    this.Stock = f.Stock;
                    this.Producto = Productos.Get(this.Stock.IdProducto);
                    txUM.Text = this.Producto.UnidadMedida;
                    txProductoEnStock.Text = Stock.ToString(Producto);
                    txCantidad.Text = this.Stock.Cantidad.ToString();
                }
            }
        }

        private void picStockDetalle_Click(object sender, EventArgs e)
        {
            //Mostrar Item del Stock.
        }

        private void btCancelar_Click(object sender, EventArgs e)
        {
            Stock = null;
            Producto = null;
            Item = null;

            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void btAceptar_Click(object sender, EventArgs e)
        {
            if (Validations())
            {
                Item = new  ValeConsumoDevolucionItemDTO();

                Item.Activo = true;
                Item.Cantidad = FormsHelper.StN(txCantidad.Text); // nuCantidad.Value;
                Item.Id = 0;
                Item.IdValeConsumoDevolucion = 0;
                Item.IdStock = Stock.Id;
                Item.Obs = txObs.Text;
                Item.IdProducto = Stock.IdProducto;
                Item.NroAnalisis = Stock.NroAnalisis;
                
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
            else
            {
                errP.SetError(btAceptar, "Campos obligatorios sin cargar");
            }
        }

        private void cbPuerto_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                //--
                if (serialPort1.IsOpen)
                    serialPort1.Close();

                //-
                serialPort1.PortName = cbPuerto.Text; // "COM1";
                serialPort1.BaudRate = 9600;

                serialPort1.Open();
                if (serialPort1.IsOpen)
                {
                    //lstPuertos.Enabled = false;
                    //buttonStart.Enabled = false;
                    //buttonStop.Enabled = true;
                    //textBox1.ReadOnly = false;
                }
            }
            catch (Exception ex)
            {
                FormsHelper.MsgErrorInesperado(ex);
            }
        }

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            RxString = serialPort1.ReadExisting();
            this.Invoke(new EventHandler(LeerBalanza));
        }

        private void LeerBalanza(object sender, EventArgs e)
        {
            try
            {
                string[] lineas = RxString.Split(new string[] { "\n" },  StringSplitOptions.RemoveEmptyEntries);

                txBruto.Text = string.Empty;
                txTara.Text = string.Empty;
                txNeto.Text = string.Empty;

                foreach (var linea in lineas)
                {
                    var fila = linea.Trim().ToUpper();


                    if (fila.StartsWith("G"))
                    {
                        txUM2.Text = fila.Substring(fila.LastIndexOf(" ")).Trim();

                        var peso = fila.Substring(1, fila.LastIndexOf(" "));
                        decimal g = FormsHelper.StN(peso);
                        txBruto.Text = g.ToString(FormsHelper.formatoMonto);
                    }
                    else if (fila.StartsWith("T"))
                    {
                        txUM2.Text = fila.Substring(fila.LastIndexOf(" ")).Trim();

                        var peso = fila.Substring(1, fila.LastIndexOf(" "));
                        decimal t = FormsHelper.StN(peso);
                        txTara.Text = t.ToString(FormsHelper.formatoMonto);
                    } 
                    else if (fila.StartsWith("N"))
                    {
                        txUM2.Text = fila.Substring(fila.LastIndexOf(" ")).Trim();

                        var peso = fila.Substring(1, fila.LastIndexOf(" "));
                        decimal n = FormsHelper.StN(peso);
                        txNeto.Text = n.ToString(FormsHelper.formatoMonto);

                        //--
                        txCantidad.Text = txNeto.Text;
                    }
                }
            }
            catch (Exception ex)
            {
                FormsHelper.MsgErrorInesperado(ex);
            }
        }

        private void frmValeItem_FormClosing(object sender, FormClosingEventArgs e)
        {
            //--
            if (serialPort1.IsOpen)
                serialPort1.Close();
        }

        private void btTest_Click(object sender, EventArgs e)
        {
            RxString = 
@"G            1.98 kg
T            0.24 kg
N            1.74 kg



";
            this.Invoke(new EventHandler(LeerBalanza));
        }
    }
}
